package com.eduagent.xwqeduagent.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.eduagent.xwqeduagent.api.characterRecognition.PhotographySpeedCalculation.PhotographySpeedCalculationAPI;
import com.eduagent.xwqeduagent.api.characterRecognition.PhotographySpeedCalculation.PhotographySpeedCalculationResult;
import com.eduagent.xwqeduagent.api.characterRecognition.PhotographySpeedCalculation.PhotographySpeedCalculationResult.SpeedCalculationItem;
import com.eduagent.xwqeduagent.common.BaseResponse;
import com.eduagent.xwqeduagent.common.ResultUtils;
import com.eduagent.xwqeduagent.exception.ErrorCode;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 拍照速算识别控制器
 */
@Slf4j
@RestController
@RequestMapping("/speed-calculation")
@Tag(name = "拍照速算", description = "拍照速算识别相关接口")
public class PhotographySpeedCalculationController {

    @Value("${xunfei.api.speed-calculation.appid:637d1630}")
    private String appId;

    @Value("${xunfei.api.speed-calculation.apikey:8bd0514cb66802c719bbf34a908a0119}")
    private String apiKey;

    @Value("${xunfei.api.speed-calculation.apisecret:NzUyY2Y3OTYwYjAyMGExODc5OTM1ZGZl}")
    private String apiSecret;

    /**
     * 上传图片识别速算题
     *
     * @param file 图片文件
     * @return 识别结果
     */
    @Operation(summary = "速算题识别", description = "通过上传图片识别速算题")
    @PostMapping(value = "/recognize", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public BaseResponse<?> recognizeSpeedCalculation(@Parameter(description = "图片文件，支持jpg/png/bmp格式，最大4M") @RequestPart("file") MultipartFile file) {
        try {
            // 检查API配置
            if (appId == null || appId.isEmpty() || apiKey == null || apiKey.isEmpty() || apiSecret == null || apiSecret.isEmpty()) {
                log.error("讯飞平台配置缺失，请配置xunfei.api.speed-calculation相关参数");
                return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "系统配置错误，请联系管理员");
            }

            // 检查文件是否为空
            if (file.isEmpty()) {
                return ResultUtils.error(ErrorCode.PARAMS_ERROR, "上传文件为空");
            }

            // 检查文件大小
            if (file.getSize() > 4 * 1024 * 1024) {
                return ResultUtils.error(ErrorCode.PARAMS_ERROR, "文件大小超过4M限制");
            }

            // 检查文件类型
            String contentType = file.getContentType();
            if (contentType == null || !(contentType.contains("jpeg") || contentType.contains("png") || contentType.contains("bmp"))) {
                return ResultUtils.error(ErrorCode.PARAMS_ERROR, "仅支持jpg/png/bmp格式图片");
            }

            // 创建API实例
            PhotographySpeedCalculationAPI api = new PhotographySpeedCalculationAPI(appId, apiKey, apiSecret);

            // 读取上传的文件内容
            byte[] fileContent = file.getBytes();

            // 调用API进行识别
            String jsonResult = api.recognizeFromByteArray(fileContent);
            log.info("拍照速算识别API返回结果：{}", jsonResult);

            // 从JSON中提取公式内容和正确性判断
            JSONObject jsonObject = JSON.parseObject(jsonResult);
            if (jsonObject.getIntValue("code") == 0 && jsonObject.containsKey("data")) {
                JSONObject dataObj = jsonObject.getJSONObject("data");
                if (dataObj.containsKey("ITRResult")) {
                    JSONObject itrResult = dataObj.getJSONObject("ITRResult");
                    
                    // 获取公式内容
                    List<Map<String, Object>> formulas = new ArrayList<>();
                    if (itrResult.containsKey("recog_result")) {
                        JSONArray recogResults = itrResult.getJSONArray("recog_result");
                        if (recogResults.size() > 0) {
                            JSONObject firstResult = recogResults.getJSONObject(0);
                            if (firstResult.containsKey("line_word_result")) {
                                JSONArray wordResults = firstResult.getJSONArray("line_word_result");
                                
                                // 获取正确性判断信息
                                List<Integer> totalScores = new ArrayList<>();
                                List<Integer> recRejections = new ArrayList<>();
                                if (itrResult.containsKey("multi_line_info")) {
                                    JSONObject multiLineInfo = itrResult.getJSONObject("multi_line_info");
                                    if (multiLineInfo.containsKey("imp_line_info")) {
                                        JSONArray impLineInfos = multiLineInfo.getJSONArray("imp_line_info");
                                        for (int i = 0; i < impLineInfos.size(); i++) {
                                            JSONObject impLineInfo = impLineInfos.getJSONObject(i);
                                            totalScores.add(impLineInfo.getInteger("total_score"));
                                            recRejections.add(impLineInfo.getInteger("rec_rejection"));
                                        }
                                    }
                                }
                                
                                // 将公式内容和正确性信息结合
                                int size = Math.min(wordResults.size(), totalScores.size());
                                for (int i = 0; i < size; i++) {
                                    JSONObject wordResult = wordResults.getJSONObject(i);
                                    if (wordResult.containsKey("word_content")) {
                                        JSONArray wordContents = wordResult.getJSONArray("word_content");
                                        if (wordContents.size() > 0) {
                                            Map<String, Object> formulaInfo = new HashMap<>();
                                            formulaInfo.put("formula", wordContents.getString(0));
                                            formulaInfo.put("isCorrect", totalScores.get(i) == 1);
                                            formulaInfo.put("isReliable", recRejections.get(i) == 0);
                                            formulas.add(formulaInfo);
                                        }
                                    }
                                }
                                return ResultUtils.success(formulas);
                            }
                        }
                    }
                }
            }
            
            // 如果未找到公式内容
            return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "未找到识别内容");

        } catch (Exception e) {
            log.error("处理上传文件失败", e);
            return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "处理上传文件失败：" + e.getMessage());
        }
    }
} 